package ui;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;

import util.ImagePanel;
import util.JCalendar;
import util.Number;
import util.PdfFilePrint;
import controller.ProjectController;
import controller.CustomerController;
import controller.ServiceController;
import controller.SubContractorController;
import controller.ItemController;
import model.Customer;
import model.Item;
import model.Project;
import model.ProjectSubContractor;
import model.ProjectUsedItem;
import model.Service;
import model.SubContractor;

import javax.swing.border.TitledBorder;
import javax.swing.JSeparator;

public class ProjectUI implements ActionListener
{
	private boolean startup = false;

	private static ProjectUI instance = null;

	private ProjectController projCtrl;
	private SubContractorController subContractorCtrl;
	private CustomerController custCtrl;
	private ItemController itemCtrl;
	private ServiceController svCtrl;

	private JFrame frameProjectUI;

	private JTabbedPane tabbedPane;

	private Image image;

	private ImagePanel newProj;
	private ImagePanel allProj;
	private ImagePanel editProj;

	private JPanel panel_1;

	private JScrollPane descrScroll;
	private JScrollPane commScroll;
	private JScrollPane subScroll;
	private JScrollPane editSubScroll;

	private JTable allProjTable;
	private JTable editProjTable;
	private JTable subTable;
	private JTable editSubTable;

	private DefaultTableModel allSubsModel;
	private DefaultTableModel allProjTableModel;
	private DefaultTableModel editProjTableModel;
	private DefaultTableModel editSubTableModel;


	private JScrollPane allProjTableScroll;
	private JScrollPane editProjTableScroll;

	private JComboBox<String> allProjSearch;
	private JComboBox<String> newProjCustomerSelection;
	private JComboBox<String> subContrBox;
	private JComboBox<String> editProjCombo;
	private JComboBox<String> editProjItemCombobox;
	private JComboBox<String> subCombo;

	private JLabel lblItemPrice;

	private JButton createProj;
	private JButton clearSearch;
	private JButton clearSearch_1;
	private JButton editProjBtn;
	private JButton btnSaveChanges;
	private JButton btnDeleteItem;
	private JButton btnEditItem;
	private JButton btnAddSub;
	private JButton btnGetDescription;

	private JTextField projSearch;
	private JTextField projDrawNoText;
	private JTextField projQuantityText;
	private JTextField linkText;
	private JTextField dimensionsText;
	private JTextField cusPriceText;
	private JTextField projNameText;
	private JTextField editProjQuantity;

	private JCheckBox allProjCheckbox;

	private Project editingProject;
	private JButton btnAddItem;

	private JButton btnChangeStatus;
	private JButton btnGetComments;
	private JButton btnEditProject;
	private JButton btnOpenLink;
	private JButton btnAdd;
	private JButton statistics;

	private JCalendar cal;

	private JTextPane comms;
	private JTextPane descr;

	private ArrayList<SubContractor> chosenEdit = new ArrayList<SubContractor>();
	private ArrayList<SubContractor> chosenCreate = new ArrayList<SubContractor>();

	private ArrayList<Double> priceEdit = new ArrayList<Double>();
	private ArrayList<Double> priceCreate = new ArrayList<Double>();

	private JTextField newPrice;
	private JLabel lblPrice_1;
	private JTextField editPrice;
	private JLabel lblSubcontractorPrice;
	private JButton btnBack;

	private backButton back;
	private JButton btnPrint;

	public void display()
	{
		frameProjectUI.setSize(850, 520);
		frameProjectUI.setVisible(true);
		frameProjectUI.setResizable(false);
		frameProjectUI.setLocationRelativeTo(null);
	}

	public ProjectUI()
	{
		back = new backButton();
		back.setNumber("11");
		frameProjectUI = new MainWindow();

		frameProjectUI.setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

		projCtrl = new ProjectController();
		subContractorCtrl = new SubContractorController();
		custCtrl = new CustomerController();
		itemCtrl = new ItemController();
		svCtrl = new ServiceController();

		JLabel proj = new JLabel ("PROJECTS");
		proj.setBounds(9, 1, 116, 28);
		proj.setForeground(Color.white);
		proj.setFont(new Font("Dialog", Font.BOLD, 20));

		chosenEdit = new ArrayList<SubContractor>();
		chosenCreate = new ArrayList<SubContractor>();

		priceEdit = new ArrayList<Double>();
		priceCreate = new ArrayList<Double>();


		frameProjectUI.getContentPane().add(proj);

		statistics = new JButton();
		statistics.setLocation(734, 449);
		statistics.setSize(100, 20);
		statistics.setOpaque(false);
		statistics.setText("Statistics");
		statistics.addActionListener(this);

		frameProjectUI.getContentPane().add(statistics);

		try
		{
			image = ImageIO.read(new File("img/background/background.jpg"));
		}
		catch(Exception e)
		{
			msgError(null, "Could not load background");
		}

		tabbedPane = new JTabbedPane();
		tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
		tabbedPane.setBounds(0, 31, 850, 414);

		frameProjectUI.getContentPane().add(tabbedPane);

		allProj = new ImagePanel(image);
		newProj = new ImagePanel(image);



		clearSearch = new JButton("Clear Search");
		clearSearch.setOpaque(false);
		clearSearch.addActionListener(this);

		editProjBtn = new JButton("Edit Project");
		editProjBtn.setOpaque(false);
		editProjBtn.addActionListener(this);

		projSearch = new JTextField();
		projSearch.getDocument().addDocumentListener(
				new DocumentListener()
				{
					@Override
					public void changedUpdate(DocumentEvent arg0)
					{
						searchProjects();
					}

					@Override
					public void insertUpdate(DocumentEvent arg0)
					{
						searchProjects();
					}

					@Override
					public void removeUpdate(DocumentEvent arg0)
					{
						searchProjects();
					}
				}
				);

		JLabel searchBy = new JLabel("Search for:");
		JLabel searchWith = new JLabel("Search with:");

		allProjSearch = new JComboBox<String>();
		allProjSearch.addActionListener(this);
		allProjSearch.addItem("Everything");
		allProjSearch.addItem("Name");
		allProjSearch.addItem("SubContractor");
		allProjSearch.addItem("Customer");
		allProjSearch.addItem("City");
		allProjSearch.addItem("Country");

		projCtrl = new ProjectController();

		String allProjColumns[] = {"#","Drawing Number", "Name","Dimensions" ,"Price", "Quantity", "Deadline", "City", "Country","Customer"};

		allProjTableModel = new DefaultTableModel(null, allProjColumns);

		allProjTable = new JTable(allProjTableModel)
		{
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int rowIndex, int colIndex)
			{
				return false;
			}

			public Class<?> getColumnClass(int column)   
			{   
				return getValueAt(0, column).getClass();
			}
		};

		Dimension d = allProjTable.getPreferredSize();
		double width = d.width / allProjColumns.length;
		double [] width_2 = {0.3, 1.3, 1.3, 1.4, 0.3, 0.5, 0.6, 0.6, 0.9, 1.1};

		for (int i = 0; i < allProjColumns.length; i++)
			allProjTable.getColumnModel().getColumn(i).setPreferredWidth((int) (width*width_2[i]));

		allProjTable.setAutoCreateRowSorter(true);

		allProjTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		allProjTableScroll = new JScrollPane(allProjTable);

		clearSearch_1 = new JButton("Clear Search");
		clearSearch_1.setOpaque(false);
		clearSearch_1.addActionListener(this);

		allProjCheckbox = new JCheckBox("Show only active projects");
		allProjCheckbox.addActionListener(this);
		allProjCheckbox.setOpaque(false);
		allProjCheckbox.setSelected(true);

		btnChangeStatus = new JButton("Change status");
		btnChangeStatus.setOpaque(false);
		btnChangeStatus.addActionListener(this);

		btnGetDescription = new JButton("Get Description");
		btnGetDescription.setOpaque(false);
		btnGetDescription.addActionListener(this);

		btnGetComments = new JButton("Get Comments");
		btnGetComments.setOpaque(false);
		btnGetComments.addActionListener(this);

		btnEditProject = new JButton("Edit Project");
		btnEditProject.addActionListener(this);
		btnEditProject.setOpaque(false);

		btnOpenLink = new JButton("Open Link");
		btnOpenLink.setOpaque(false);
		btnOpenLink.addActionListener(this);
		String editProjColumns [] = {"#", "Name", "Price",  "Quantity", "Total"};


		editProjTableModel = new DefaultTableModel(null, editProjColumns);
		width = d.width / editProjColumns.length;
		double [] width_3 = {0.3, 3, 1, 1, 1};

		editProjTable = new JTable(editProjTableModel)
		{
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int rowIndex, int colIndex)
			{
				return false;
			}
		};

		d = editProjTable.getPreferredSize();

		editProjTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		editProjTableScroll = new JScrollPane(editProjTable);


		for (int i = 0; i < editProjColumns.length; i++)
			editProjTable.getColumnModel().getColumn(i).setPreferredWidth((int) (width*width_3[i]));

		JLabel projName = new JLabel("Name:");
		projName.setBounds(83, 19, 31, 14);
		JLabel projDrawNo = new JLabel("Drawing Number:");
		projDrawNo.setBounds(83, 95, 83, 14);
		JLabel projQuantity = new JLabel("Quantity:");
		projQuantity.setBounds(83, 68, 46, 14);
		JLabel projDescr = new JLabel("Description:");
		projDescr.setBounds(424, 264, 57, 17);
		JLabel dimensions = new JLabel("Dimensions:");
		dimensions.setBounds(83, 120, 63, 19);
		JLabel projCus = new JLabel("Customer:");
		projCus.setBounds(83, 179, 50, 14);
		JLabel cusPrice = new JLabel("Price:");
		cusPrice.setBounds(83, 44, 27, 14);
		JLabel projLink = new JLabel("Project Link:");
		projLink.setBounds(83, 150, 74, 14);
		JLabel projComments = new JLabel("Comments:");
		projComments.setBounds(423, 176, 54, 14);
		JLabel lblSubcontractor = new JLabel("SubContractor:");
		lblSubcontractor.setBounds(83, 208, 74, 14);

		createProj = new JButton();
		createProj.setBounds(244, 357, 103, 23);
		createProj.setText("Create Project");
		createProj.setOpaque(false);
		createProj.addActionListener(this);

		projDrawNoText = new JTextField();
		projDrawNoText.setBounds(188, 90, 225, 20);
		projQuantityText = new JTextField();
		projQuantityText.setBounds(189, 62, 224, 20);
		dimensionsText = new JTextField();
		dimensionsText.setBounds(188, 117, 225, 20);
		linkText = new JTextField();
		linkText.setBounds(188, 145, 225, 20);
		cusPriceText = new JTextField();
		cusPriceText.setBounds(189, 36, 224, 20);
		projNameText = new JTextField();
		projNameText.setBounds(188, 11, 225, 20);

		descr = new JTextPane();
		comms = new JTextPane();


		newProjCustomerSelection = new JComboBox<String>();
		newProjCustomerSelection.setBounds(188, 173, 225, 20);
		populateCustomers(newProjCustomerSelection);

		cal = new JCalendar();
		cal.setBounds(424, 12, 312, 149);
		cal.setBorder(new TitledBorder(null, "Deadline", TitledBorder.LEADING, TitledBorder.BELOW_TOP, null, null));


		descrScroll = new JScrollPane();
		descrScroll.setBounds(501, 266, 236, 78);
		descrScroll.setViewportView(descr);

		commScroll = new JScrollPane();
		commScroll.setBounds(500, 177, 236, 78);
		commScroll.setViewportView(comms);

		subCombo = new JComboBox<String>();
		subCombo.setBounds(188, 202, 158, 20);

		populateSubContractors(subCombo);

		btnAdd = new JButton();
		btnAdd.setBounds(356, 201, 57, 23);
		btnAdd.addActionListener(this);
		btnAdd.setText("Add");
		btnAdd.setOpaque(false);

		String column[] = {"id", "name"};

		allSubsModel = new DefaultTableModel(null, column);

		subTable = new JTable(allSubsModel)
		{
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int rowIndex, int colIndex)
			{
				return false;
			}
		};
		Dimension dimS = subTable.getPreferredSize();
		double widthSub = dimS.width / column.length;
		double [] width_2Sub = {0.2,1.2};

		for (int i = 0; i < column.length; i++)
			subTable.getColumnModel().getColumn(i).setPreferredWidth((int) (widthSub*width_2Sub[i]));

		subTable.setAutoCreateRowSorter(true);

		subTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		subScroll = new JScrollPane();
		subScroll.setBounds(188, 264, 225, 81);
		subScroll.setViewportView(subTable);

		editProj = new ImagePanel(image);

		JPanel infoProj = new JPanel();
		infoProj.setOpaque(false);
		infoProj.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Project info", TitledBorder.LEADING, TitledBorder.BELOW_TOP, null, null));

		panel_1 = new JPanel();
		panel_1.setOpaque(false);
		panel_1.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Material Info", TitledBorder.LEADING, TitledBorder.BELOW_TOP, null, null));

		JLabel lblItem = new JLabel("Material:");
		JLabel lblQuantity = new JLabel("Quantity:");

		editProjItemCombobox = new JComboBox<String>();

		editProjQuantity = new JTextField();
		editProjQuantity.setColumns(10);

		btnAddItem = new JButton("Add item");
		btnAddItem.addActionListener(this);
		btnAddItem.setOpaque(false);

		JSeparator separator = new JSeparator();
		JLabel lblProjectSubcontractor = new JLabel("SubContractor:");
		JLabel lblSelectProject = new JLabel("Select project:");

		subContrBox= new JComboBox<String>();

		populateSubContractors(subContrBox);

		editSubTableModel = new DefaultTableModel(null,column);

		editSubTable = new JTable(editSubTableModel)
		{
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int rowIndex, int colIndex)
			{
				return false;
			}
		};
		for (int i = 0; i < column.length; i++)
			editSubTable.getColumnModel().getColumn(i).setPreferredWidth((int) (widthSub*width_2Sub[i]));

		editSubTable.setAutoCreateRowSorter(true);

		editSubTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		editSubScroll = new JScrollPane();
		editSubScroll.setViewportView(editSubTable);

		btnSaveChanges = new JButton("Save changes");
		btnSaveChanges.setOpaque(false);
		btnSaveChanges.addActionListener(this);

		editProjCombo = new JComboBox<String>();
		editProjCombo.addActionListener(this);

		JSeparator separator_1 = new JSeparator();

		btnDeleteItem = new JButton("Delete item");
		btnDeleteItem.setOpaque(false);
		btnDeleteItem.addActionListener(this);

		btnEditItem = new JButton("Edit item");
		btnEditItem.setOpaque(false);
		btnEditItem.addActionListener(this);

		lblItemPrice = new JLabel("0.0");

		btnAddSub = new JButton("Add");
		btnAddSub.addActionListener(this);
		btnAddSub.setOpaque(false);

		tabbedPane.addTab("All Projects", null, allProj, null);
		GroupLayout gl_allProj = new GroupLayout(allProj);
		gl_allProj.setHorizontalGroup(
				gl_allProj.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_allProj.createSequentialGroup()
						.addGap(11)
						.addGroup(gl_allProj.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_allProj.createSequentialGroup()
										.addComponent(searchWith)
										.addGap(4)
										.addComponent(allProjSearch, GroupLayout.PREFERRED_SIZE, 126, GroupLayout.PREFERRED_SIZE)
										.addGap(6)
										.addComponent(allProjCheckbox)
										.addGap(183)
										.addComponent(btnGetComments, GroupLayout.PREFERRED_SIZE, 117, GroupLayout.PREFERRED_SIZE)
										.addGap(10)
										.addComponent(btnChangeStatus, GroupLayout.PREFERRED_SIZE, 117, GroupLayout.PREFERRED_SIZE))
										.addGroup(gl_allProj.createSequentialGroup()
												.addComponent(searchBy)
												.addGap(10)
												.addComponent(projSearch, GroupLayout.PREFERRED_SIZE, 126, GroupLayout.PREFERRED_SIZE)
												.addGap(6)
												.addComponent(clearSearch_1, GroupLayout.PREFERRED_SIZE, 105, GroupLayout.PREFERRED_SIZE)
												.addGap(100)
												.addComponent(btnOpenLink, GroupLayout.PREFERRED_SIZE, 117, GroupLayout.PREFERRED_SIZE)
												.addGap(10)
												.addComponent(btnGetDescription, GroupLayout.PREFERRED_SIZE, 117, GroupLayout.PREFERRED_SIZE)
												.addGap(10)
												.addComponent(btnEditProject, GroupLayout.PREFERRED_SIZE, 117, GroupLayout.PREFERRED_SIZE))
												.addComponent(allProjTableScroll, GroupLayout.PREFERRED_SIZE, 772, GroupLayout.PREFERRED_SIZE)))
				);
		gl_allProj.setVerticalGroup(
				gl_allProj.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_allProj.createSequentialGroup()
						.addGap(10)
						.addGroup(gl_allProj.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_allProj.createSequentialGroup()
										.addGap(4)
										.addComponent(searchWith))
										.addGroup(gl_allProj.createSequentialGroup()
												.addGap(2)
												.addComponent(allProjSearch, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
												.addGroup(gl_allProj.createSequentialGroup()
														.addGap(1)
														.addComponent(allProjCheckbox))
														.addComponent(btnGetComments)
														.addComponent(btnChangeStatus))
														.addGap(3)
														.addGroup(gl_allProj.createParallelGroup(Alignment.LEADING)
																.addComponent(searchBy)
																.addGroup(gl_allProj.createSequentialGroup()
																		.addGap(1)
																		.addComponent(projSearch, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
																		.addComponent(clearSearch_1)
																		.addComponent(btnOpenLink)
																		.addComponent(btnGetDescription)
																		.addComponent(btnEditProject))
																		.addGap(7)
																		.addComponent(allProjTableScroll, GroupLayout.PREFERRED_SIZE, 247, GroupLayout.PREFERRED_SIZE))
				);
		allProj.setLayout(gl_allProj);
		tabbedPane.addTab("New Project", null, newProj, null);

		newPrice = new JTextField();
		newPrice.setBounds(188, 233, 225, 20);

		lblPrice_1 = new JLabel("SubContractor Price:");
		lblPrice_1.setBounds(83, 235, 100, 14);
		newProj.setLayout(null);
		newProj.add(projName);
		newProj.add(cusPrice);
		newProj.add(projQuantity);
		newProj.add(projDrawNo);
		newProj.add(dimensions);
		newProj.add(projLink);
		newProj.add(projNameText);
		newProj.add(cusPriceText);
		newProj.add(projQuantityText);
		newProj.add(projDrawNoText);
		newProj.add(dimensionsText);
		newProj.add(linkText);
		newProj.add(cal);
		newProj.add(projCus);
		newProj.add(lblSubcontractor);
		newProj.add(lblPrice_1);
		newProj.add(newProjCustomerSelection);
		newProj.add(subCombo);
		newProj.add(btnAdd);
		newProj.add(newPrice);
		newProj.add(subScroll);
		newProj.add(projComments);
		newProj.add(projDescr);
		newProj.add(commScroll);
		newProj.add(descrScroll);
		newProj.add(createProj);
		tabbedPane.addTab("Project Details", null, editProj, null);
		GroupLayout gl_editProj = new GroupLayout(editProj);
		gl_editProj.setHorizontalGroup(
				gl_editProj.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_editProj.createSequentialGroup()
						.addContainerGap()
						.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 357, GroupLayout.PREFERRED_SIZE)
						.addGap(18)
						.addComponent(infoProj, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addGap(62))
				);
		gl_editProj.setVerticalGroup(
				gl_editProj.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_editProj.createSequentialGroup()
						.addGap(11)
						.addGroup(gl_editProj.createParallelGroup(Alignment.TRAILING, false)
								.addComponent(infoProj, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addComponent(panel_1, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
				);

		editPrice = new JTextField();
		editPrice.setColumns(10);

		lblSubcontractorPrice = new JLabel("SubContractor Price:");



		GroupLayout gl_infoProj = new GroupLayout(infoProj);
		gl_infoProj.setHorizontalGroup(
				gl_infoProj.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_infoProj.createSequentialGroup()
						.addGroup(gl_infoProj.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_infoProj.createSequentialGroup()
										.addGap(10)
										.addComponent(lblProjectSubcontractor))
										.addGroup(gl_infoProj.createSequentialGroup()
												.addContainerGap()
												.addComponent(lblSubcontractorPrice, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE))
												.addGroup(gl_infoProj.createSequentialGroup()
														.addGap(10)
														.addComponent(lblSelectProject)))
														.addPreferredGap(ComponentPlacement.RELATED)
														.addGroup(gl_infoProj.createParallelGroup(Alignment.LEADING, false)
																.addComponent(editProjCombo, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
																.addGroup(gl_infoProj.createSequentialGroup()
																		.addComponent(subContrBox, GroupLayout.PREFERRED_SIZE, 154, GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
																		.addComponent(btnAddSub, GroupLayout.PREFERRED_SIZE, 69, GroupLayout.PREFERRED_SIZE))
																		.addComponent(editPrice)
																		.addComponent(btnSaveChanges)
																		.addComponent(editSubScroll, GroupLayout.PREFERRED_SIZE, 237, GroupLayout.PREFERRED_SIZE))
																		.addGap(31))
																		.addComponent(separator_1, GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
				);
		gl_infoProj.setVerticalGroup(
				gl_infoProj.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_infoProj.createSequentialGroup()
						.addComponent(separator_1, GroupLayout.PREFERRED_SIZE, 8, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addGroup(gl_infoProj.createParallelGroup(Alignment.LEADING)
								.addComponent(lblSelectProject)
								.addComponent(editProjCombo, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE))
								.addGap(10)
								.addGroup(gl_infoProj.createParallelGroup(Alignment.LEADING)
										.addComponent(lblProjectSubcontractor)
										.addGroup(gl_infoProj.createSequentialGroup()
												.addGap(2)
												.addGroup(gl_infoProj.createParallelGroup(Alignment.BASELINE)
														.addComponent(subContrBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
														.addComponent(btnAddSub))))
														.addPreferredGap(ComponentPlacement.RELATED)
														.addGroup(gl_infoProj.createParallelGroup(Alignment.LEADING)
																.addComponent(lblSubcontractorPrice)
																.addComponent(editPrice, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
																.addPreferredGap(ComponentPlacement.UNRELATED)
																.addComponent(editSubScroll, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)
																.addPreferredGap(ComponentPlacement.RELATED)
																.addComponent(btnSaveChanges)
																.addGap(47))
				);
		infoProj.setLayout(gl_infoProj);
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(
				gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
						.addGap(10)
						.addComponent(lblItem)
						.addGap(33)
						.addComponent(editProjItemCombobox, GroupLayout.PREFERRED_SIZE, 159, GroupLayout.PREFERRED_SIZE)
						.addGap(18)
						.addComponent(btnAddItem))
						.addGroup(gl_panel_1.createSequentialGroup()
								.addGap(10)
								.addComponent(lblQuantity)
								.addGap(25)
								.addComponent(editProjQuantity, GroupLayout.PREFERRED_SIZE, 163, GroupLayout.PREFERRED_SIZE))
								.addGroup(gl_panel_1.createSequentialGroup()
										.addGap(10)
										.addComponent(editProjTableScroll, GroupLayout.PREFERRED_SIZE, 234, GroupLayout.PREFERRED_SIZE)
										.addGap(18)
										.addComponent(lblItemPrice, GroupLayout.PREFERRED_SIZE, 75, GroupLayout.PREFERRED_SIZE))
										.addGroup(gl_panel_1.createSequentialGroup()
												.addGap(10)
												.addComponent(btnEditItem, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE)
												.addGap(62)
												.addComponent(btnDeleteItem))
												.addComponent(separator, GroupLayout.DEFAULT_SIZE, 351, Short.MAX_VALUE)
				);
		gl_panel_1.setVerticalGroup(
				gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
						.addComponent(separator, GroupLayout.PREFERRED_SIZE, 7, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_panel_1.createSequentialGroup()
										.addGap(3)
										.addComponent(lblItem))
										.addGroup(gl_panel_1.createSequentialGroup()
												.addGap(1)
												.addComponent(editProjItemCombobox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
												.addComponent(btnAddItem))
												.addGap(6)
												.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
														.addGroup(gl_panel_1.createSequentialGroup()
																.addGap(3)
																.addComponent(lblQuantity))
																.addComponent(editProjQuantity, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
																.addGap(11)
																.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
																		.addComponent(editProjTableScroll, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE)
																		.addGroup(gl_panel_1.createSequentialGroup()
																				.addGap(1)
																				.addComponent(lblItemPrice)))
																				.addGap(6)
																				.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
																						.addComponent(btnEditItem)
																						.addComponent(btnDeleteItem)))
				);
		panel_1.setLayout(gl_panel_1);
		editProj.setLayout(gl_editProj);

		btnBack = new JButton();
		btnBack.addActionListener(this);
		btnBack.setText("Back");
		btnBack.setOpaque(false);
		btnBack.setBounds(9, 448, 100, 20);

		frameProjectUI.getContentPane().add(btnBack);

		btnPrint = new JButton();
		btnPrint.addActionListener(this);
		btnPrint.setText("Print");
		btnPrint.setOpaque(false);
		btnPrint.setBounds(624, 448, 100, 20);
		frameProjectUI.getContentPane().add(btnPrint);

		populateProjects();
		searchProjects();
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		frameProjectUI.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

		if (e.getSource() == allProjSearch)
		{
			if (startup)
			{
				projSearch.setText(null);

				searchProjects();
			}
		}
		else if(e.getSource() == btnOpenLink)
		{
			try
			{
				openLink();
			} catch (IOException e1)
			{
				e1.printStackTrace();
			}
		}
		else if (e.getSource() == clearSearch_1)
		{
			allProjSearch.setSelectedIndex(0);
			projSearch.setText(null);
			allProjCheckbox.setSelected(true);
		}
		else if (e.getSource() == editProjCombo)
		{
			if (editProjCombo.getSelectedIndex() > 0)
			{
				tableClearList(editProjTable);
				tableClearList(subTable);

				try
				{
					editingProject = projCtrl.findProjectByName(editProjCombo.getSelectedItem().toString());

				}
				catch (SQLException ex)
				{
					msgError(editProj, "Could not load project");
				}
				getSubsFromProject(editingProject);
				updateEditProject();
				searchProjects();
			}

		}
		else if (e.getSource() == allProjCheckbox)
		{
			searchProjects();
		}
		else if(e.getSource() == btnEditProject)
		{
			updateProjectInfo();
			searchProjects();
		}
		else if(e.getSource() == btnGetComments)
		{
			getComments();
		}
		else if(e.getSource() == btnGetDescription)	
		{
			getDescription();
		}
		else if (e.getSource() == createProj)
		{

			createProject();
			priceCreate.clear();
			searchProjects();
		}
		else if (e.getSource() == btnAddItem)
		{
			addProductUsedItem();
			updateProjectPrice();
		}
		else if (e.getSource() == btnDeleteItem)
		{
			deleteProductUsedItem();
			updateProjectPrice();
		}
		else if (e.getSource() == btnEditItem)
		{
			updateProductUsedItem();
			updateProjectPrice();
		}
		else if (e.getSource() == btnSaveChanges)
		{
			addEditedSubs();
			chosenEdit.clear();
			priceEdit.clear();
		}
		else if (e.getSource() == btnChangeStatus)
		{
			updateProjectstatus();

		}
		else if(e.getSource() == btnAdd)
		{
			boolean check = checkInfoGeneral(newPrice);
			if(check)
			{
				priceCreate.add(Double.parseDouble(newPrice.getText().trim()));
				allSubsTable(subCombo,allSubsModel);
				newPrice.setText(null);
			}
			else
			{
				msgError(newProj, "You did not input the subcontractor price properly");
			}
		}
		else if(e.getSource() == btnAddSub)
		{
			boolean check = checkInfoGeneral(editPrice);
			if(check)
			{
				priceEdit.add(Double.parseDouble(editPrice.getText().trim()));
				allSubsTable(subContrBox,allSubsModel);
				editPrice.setText(null);
			}
			else
			{
				msgError(editProj, "You did not input the subcontractor price properly");
			}

		}
		else if(e.getSource() == statistics)
		{
			StatisticsUI stats = StatisticsUI.getInstance();
			stats.display();
			frameProjectUI.setVisible(false);
		}
		else if(e.getSource() == btnBack)
		{
			back.goBack(back.getNumber());
		}
		else if(e.getSource() == btnPrint)
		{
			printProjectPDF();
		}

		frameProjectUI.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
	}

	private void printProjectPDF()
	{
		if (allProjTable.getRowCount() > 0)
		{
			ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();

			String columns[] = { "#","Drawing Number", "Name", "Dimensions", "Price", "Quantity", "Deadline", "City", "Country", "Customer" };

			ArrayList<String> projectID = new ArrayList<String>();
			ArrayList<String> projectDrawingNo = new ArrayList<String>();
			ArrayList<String> projectName = new ArrayList<String>();
			ArrayList<String> projectDimension = new ArrayList<String>();
			ArrayList<String> projectPrice = new ArrayList<String>();
			ArrayList<String> projectQuantity = new ArrayList<String>();
			ArrayList<String> projectDeadline = new ArrayList<String>();
			ArrayList<String> projectCity = new ArrayList<String>();
			ArrayList<String> projectCountry = new ArrayList<String>();
			ArrayList<String> projectCustomer = new ArrayList<String>();

			list.add(projectID);
			list.add(projectDrawingNo);
			list.add(projectName);
			list.add(projectDimension);
			list.add(projectPrice);
			list.add(projectQuantity);
			list.add(projectDeadline);
			list.add(projectCity);
			list.add(projectCountry);
			list.add(projectCustomer);

			for(int i = 0; i < allProjTable.getRowCount(); i++)
			{
				list.get(0).add(String.valueOf(allProjTable.getValueAt(i, 0)));
				list.get(1).add(String.valueOf(allProjTable.getValueAt(i, 1)));
				list.get(2).add(String.valueOf(allProjTable.getValueAt(i, 2)));
				list.get(3).add(String.valueOf(allProjTable.getValueAt(i, 3)));
				list.get(4).add(String.valueOf(allProjTable.getValueAt(i, 4)));
				list.get(5).add(String.valueOf(allProjTable.getValueAt(i, 5)));
				list.get(6).add(String.valueOf(allProjTable.getValueAt(i, 6)));
				list.get(7).add(String.valueOf(allProjTable.getValueAt(i, 7)));
				list.get(8).add(String.valueOf(allProjTable.getValueAt(i, 8)));
				list.get(9).add(String.valueOf(allProjTable.getValueAt(i, 9)));
			}

			PdfFilePrint pdfPrint = new PdfFilePrint();
			boolean successPDF = pdfPrint.PDFPrint("Project", "Current Projects", "project", "Nikola", columns, list);

			if(successPDF)
				msgSuccess(null, "PDF was created successfully");
			else
				msgError(null, "There was an error creating the PDF");
		}
		else
		{
			msgError(null, "Nothing to print");
		}
	}

	private void getSubsFromProject(Project project)
	{
		ArrayList<ProjectSubContractor> sb = new ArrayList<ProjectSubContractor>();

		try
		{
			sb = projCtrl.getAllProjectSubContractor(project);
		} catch (SQLException e)
		{
			e.printStackTrace();
			msgError(editProj, "Could not retrieve the subcontractors for the project");
		}
		for(ProjectSubContractor s : sb)
		{
			editSubTableModel.addRow(
					new Object[]
							{
							s.getSub().getOutsiderID(),
							s.getSub().getName()
							}

					);
		}

	}
	private void addEditedSubs()
	{
		getSubs(editSubTableModel,chosenEdit);
		for (int i = 0 ; i < chosenEdit.size(); i++)
		{
			int done = 0;
			try
			{
				done = projCtrl.addProjectSubContractor(editingProject, chosenEdit.get(i), priceEdit.get(i));
			} catch (SQLException e)
			{
				msgError(editProj, "Could not add the subcontractors properly");
				e.printStackTrace();
			}
			if(done > 0)
			{
				msgSuccess(editProj, "SubContractors were added successfully");
			}
		}
	}


	private void allSubsTable(JComboBox<String> combo,DefaultTableModel model)
	{

		SubContractor sb = new SubContractor();
		try
		{
			sb = subContractorCtrl.searchSubContractorByName(combo.getSelectedItem().toString());
		} catch (SQLException e)
		{
			msgError(newProj,"The subContractor cannot be added properly");
			e.printStackTrace();
		}

		model.addRow(
				new Object[]
						{
						sb.getOutsiderID(),
						sb.getName()

						});
	}
	private void updateProjectstatus()
	{
		if (allProjTable.getSelectedRow() > -1)
		{
			try
			{
				int projectID = Integer.valueOf(String.valueOf(allProjTable.getValueAt(allProjTable.getSelectedRow(), 0)));
				int success = projCtrl.activateProject(projectID);

				if (success > 0)
				{
					searchProjects();
					populateProjects();
				}
				else
				{
					throw new SQLException();
				}
			}
			catch(SQLException e)
			{
				msgError(allProj, "There was an error while changing project status");
			}
		}
		else
		{
			msgError(allProj, "You haven't selected a project");
		}
	}

	private void updateProjectInfo()
	{
		if(allProjTable.getSelectedRow() > -1)
		{
			int projID = Integer.valueOf(String.valueOf(allProjTable.getValueAt(allProjTable.getSelectedRow(), 0)));

			Project proj = new Project();

			try
			{
				proj = projCtrl.findProjectByID(projID);
			}
			catch(SQLException e)
			{
				msgError(newProj, "Cannot retrieve needed information");
				e.printStackTrace();
			}
			JPanel paneled = new JPanel();

			JTextField editProjectName = new JTextField(proj.getName());
			JTextField editProjectDrawNo = new JTextField(String.valueOf(proj.getDrawingNo()));
			JTextField editProjectQuantity = new JTextField(String.valueOf(proj.getProdQuantity()));
			JTextField editProjectPrice = new JTextField(String.valueOf(proj.getPrice()));
			JTextField editProjectDimension = new JTextField(proj.getDimensions());
			JTextField editProjectLink = new JTextField(proj.getProjLink());

			JTextPane editProjectDescription = new JTextPane();
			editProjectDescription.setText(proj.getDescription());

			JScrollPane scrollPane_descri = new JScrollPane(editProjectDescription);
			scrollPane_descri.setViewportView(editProjectDescription);
			scrollPane_descri.setPreferredSize(new Dimension(50, 50));
			scrollPane_descri.setLocation(0, 0);

			JTextPane editProjectComments = new JTextPane();
			editProjectComments.setText(proj.getComments());

			JScrollPane scrollPane_comms = new JScrollPane(editProjectComments);
			scrollPane_comms.setViewportView(editProjectComments);
			scrollPane_comms.setPreferredSize(new Dimension(50, 50));
			scrollPane_comms.setLocation(0, 0);

			JCalendar editCal = new JCalendar();
			editCal.setBorder(new TitledBorder(null, "Deadline:", TitledBorder.LEADING, TitledBorder.BELOW_TOP, null, null));
			JComboBox <String> editCustomer = newProjCustomerSelection;

			populateCustomers(editCustomer);

			JLabel lblName = new JLabel("Name:");
			JLabel lblDrawingNumber = new JLabel("Drawing Number:");
			JLabel lblQuantity = new JLabel("Quantity:");
			JLabel lblDimension = new JLabel("Dimension:");
			JLabel lblDescription = new JLabel("Description:");
			JLabel lblCustomer = new JLabel("Customer:");
			JLabel lblLink = new JLabel("Link:");
			JLabel lblComments = new JLabel("Comments:");
			JLabel lblPrice = new JLabel("Price:");

			GroupLayout gl_paneled = new GroupLayout(paneled);
			gl_paneled.setHorizontalGroup(
					gl_paneled.createParallelGroup(Alignment.LEADING)
					.addGroup(gl_paneled.createSequentialGroup()
							.addGap(27)
							.addGroup(gl_paneled.createParallelGroup(Alignment.LEADING)
									.addGroup(gl_paneled.createSequentialGroup()
											.addGroup(gl_paneled.createParallelGroup(Alignment.LEADING)
													.addComponent(lblName)
													.addComponent(lblDrawingNumber)
													.addComponent(lblQuantity)
													.addComponent(lblDimension)
													.addComponent(lblCustomer))
													.addGap(20)
													.addGroup(gl_paneled.createParallelGroup(Alignment.LEADING)
															.addComponent(editProjectName, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)
															.addComponent(editProjectDrawNo, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)
															.addComponent(editProjectQuantity, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)
															.addComponent(editProjectDimension, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)
															.addComponent(editCustomer, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE))
															.addGap(18)
															.addComponent(lblDescription)
															.addGap(40)
															.addComponent(scrollPane_descri, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE))
															.addGroup(gl_paneled.createSequentialGroup()
																	.addGroup(gl_paneled.createParallelGroup(Alignment.LEADING)
																			.addComponent(lblLink, GroupLayout.PREFERRED_SIZE, 46, GroupLayout.PREFERRED_SIZE)
																			.addComponent(lblPrice, GroupLayout.PREFERRED_SIZE, 46, GroupLayout.PREFERRED_SIZE))
																			.addGap(57)
																			.addGroup(gl_paneled.createParallelGroup(Alignment.LEADING)
																					.addComponent(editProjectLink, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)
																					.addComponent(editProjectPrice, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)
																					.addGroup(gl_paneled.createSequentialGroup()
																							.addGap(40)
																							.addComponent(editCal, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
																							.addGap(14)
																							.addComponent(lblComments, GroupLayout.PREFERRED_SIZE, 57, GroupLayout.PREFERRED_SIZE)
																							.addGap(44)
																							.addComponent(scrollPane_comms, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE))))
					);
			gl_paneled.setVerticalGroup(
					gl_paneled.createParallelGroup(Alignment.LEADING)
					.addGroup(gl_paneled.createSequentialGroup()
							.addGap(11)
							.addGroup(gl_paneled.createParallelGroup(Alignment.LEADING)
									.addGroup(gl_paneled.createSequentialGroup()
											.addGap(3)
											.addComponent(lblName)
											.addGap(12)
											.addComponent(lblDrawingNumber)
											.addGap(12)
											.addComponent(lblQuantity)
											.addGap(12)
											.addComponent(lblDimension)
											.addGap(14)
											.addComponent(lblCustomer))
											.addGroup(gl_paneled.createSequentialGroup()
													.addComponent(editProjectName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
													.addGap(6)
													.addComponent(editProjectDrawNo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
													.addGap(6)
													.addComponent(editProjectQuantity, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
													.addGap(6)
													.addComponent(editProjectDimension, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
													.addGap(8)
													.addComponent(editCustomer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
													.addGroup(gl_paneled.createSequentialGroup()
															.addGap(3)
															.addComponent(lblDescription))
															.addGroup(gl_paneled.createSequentialGroup()
																	.addGap(3)
																	.addComponent(scrollPane_descri, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)))
																	.addGap(6)
																	.addGroup(gl_paneled.createParallelGroup(Alignment.LEADING)
																			.addGroup(gl_paneled.createSequentialGroup()
																					.addGap(3)
																					.addComponent(lblLink)
																					.addGap(14)
																					.addComponent(lblPrice))
																					.addGroup(gl_paneled.createSequentialGroup()
																							.addComponent(editProjectLink, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
																							.addGap(8)
																							.addComponent(editProjectPrice, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
																							.addGap(17)
																							.addComponent(editCal, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
																							.addGroup(gl_paneled.createSequentialGroup()
																									.addGap(3)
																									.addComponent(lblComments))
																									.addGroup(gl_paneled.createSequentialGroup()
																											.addGap(3)
																											.addComponent(scrollPane_comms, GroupLayout.PREFERRED_SIZE, 123, GroupLayout.PREFERRED_SIZE))))
					);
			paneled.setLayout(gl_paneled);


			int option = JOptionPane.showConfirmDialog(allProj, paneled, "Edit Project", JOptionPane.OK_CANCEL_OPTION);

			if(option == JOptionPane.YES_OPTION)
			{
				boolean checkName = checkInfoName(editProjectName);
				boolean checkDimension = checkInfoDimensions(editProjectDimension);
				boolean checkQuantity = checkInfoGeneral(editProjectQuantity);
				boolean checkDrawing = checkInfoGeneral(editProjectDrawNo);
				boolean validLink = checkNull(editProjectLink);

				if(validLink && checkName && checkDimension && checkQuantity && checkDrawing)
				{
					Customer cusObj = new Customer();

					try
					{
						cusObj = custCtrl.searchCustomerByName(editCustomer.getSelectedItem().toString().trim());
					}
					catch(Exception e)
					{
						msgError(allProj, "Cannot retrieve needed information");
					}
					int good = 0;
					try
					{
						good = projCtrl.updateProject(projID, editProjectName.getText().trim(), editProjectDimension.getText().trim(), Integer.valueOf(editProjectDrawNo.getText().trim()), Integer.valueOf(editProjectQuantity.getText().trim()), editProjectDescription.getText(), editCal.getPeriod(), cusObj, Double.parseDouble(editProjectPrice.getText().trim()), editProjectLink.getText().trim(), editProjectComments.getText());
					}
					catch(Exception e)
					{
						msgError(allProj, "Could not update the information. Please try again");
					}
					if(good > 0)
					{
						msgSuccess(allProj, "Project has been updated successfully");
					}
					else if(good < 0)
					{
						msgError(allProj, "There was an error updating the project");
					} // end of else

				}
			}
		} else
		{
			msgError(allProj, "You have not selected a project");
		}
	}

	private void updateProductUsedItem()
	{
		if (editProjTable.getSelectedRow() > -1)
		{
			try
			{
				int itemID = Integer.valueOf(String.valueOf(editProjTable.getValueAt(editProjTable.getSelectedRow(), 0)));
				int currentQuantity = Integer.valueOf(String.valueOf(editProjTable.getValueAt(editProjTable.getSelectedRow(), 3)));
				int stockQuantity = itemCtrl.getItemStock(itemID);
				int totalQuantity = currentQuantity + stockQuantity;

				String itemName = String.valueOf(editProjTable.getValueAt(editProjTable.getSelectedRow(), 1));

				JTextField itemQuantity = new JTextField(String.valueOf(currentQuantity));
				JPanel editItem = new JPanel(new GridLayout(0, 2));

				editItem.add(new JLabel("Item:"));
				editItem.add(new JLabel(itemName));
				editItem.add(new JLabel("Quantity:"));
				editItem.add(itemQuantity);
				editItem.add(new JLabel("Available quantity: " + String.valueOf(stockQuantity)));
				editItem.add(new JLabel(""));
				editItem.add(new JLabel("Total quantity: " + String.valueOf(totalQuantity)));

				int option = JOptionPane.showConfirmDialog(editProj, editItem, "Edit item quantity", JOptionPane.OK_CANCEL_OPTION);

				if (option == JOptionPane.YES_OPTION)
				{
					if (Number.isNumber(itemQuantity.getText()))
					{
						int amount = Integer.valueOf(itemQuantity.getText());

						if (amount > totalQuantity)
						{
							msgError(editItem, "You cannot exceed the total stock");
						}
						else if (amount == 0)
						{
							msgError(editItem, "You cannot put 0 as amount");
						}
						else 
						{
							int success = projCtrl.updateProjectUsedItem(editingProject, itemID, amount);

							if (success < 1)
								throw new SQLException();
						}
					}
					else 
					{
						msgError(editProj, "You should put an integer for quantity");
					}
				}
			}
			catch (SQLException e)
			{
				msgError(editProj, "There was an error while updating the item");
			}

			updateEditProject();
		}
		else
		{
			msgError(editProj, "You have not selected an item");
		}
	}

	private void updateProjectPrice()
	{
		try
		{
			int success = projCtrl.updateProjectPrice(editingProject.getServiceID());

			if (success < 1)
				throw new SQLException();
		}
		catch(SQLException e)
		{
			msgError(editProj, "There was an error with updating the project price");
		}
	}

	private void deleteProductUsedItem()
	{
		if (editProjTable.getSelectedRow() > -1)
		{
			try
			{
				int itemID = Integer.valueOf(String.valueOf(editProjTable.getValueAt(editProjTable.getSelectedRow(), 0)));

				int success = projCtrl.deleteProjectUsedItem(editingProject, itemID);

				if (success < 1)
					throw new SQLException();
			}
			catch(SQLException ex)
			{
				msgError(editProj, "There was an error deleting the item");
			}

			updateEditProject();
		}
		else
		{
			msgError(editProj, "You have not selected an item");
		}
	}

	private void getDescription()
	{

		if(allProjTable.getSelectedRow() > -1)
		{
			int reqID = Integer.valueOf(String.valueOf(allProjTable.getValueAt(allProjTable.getSelectedRow(), 0)));

			Service proj = new Service();
			try
			{
				proj = svCtrl.getOne(reqID);
			}
			catch(SQLException e)
			{
				msgError(allProj, "Cannoted retrieve needed information");
				e.printStackTrace();
			}
			JTextPane reqDescrField_1 = new JTextPane();
			reqDescrField_1.setText(proj.getDescription());
			JScrollPane scrollPane_1 = new JScrollPane(reqDescrField_1);
			scrollPane_1.setViewportView(reqDescrField_1);
			scrollPane_1.setPreferredSize(new Dimension(150, 150));
			scrollPane_1.setLocation(0, 0);
			JOptionPane.showConfirmDialog(allProj,scrollPane_1, "Description", JOptionPane.DEFAULT_OPTION);

		}
		else
		{
			msgError(allProj, "You have not selected a project");
		}
	}
	private void getComments()
	{

		if(allProjTable.getSelectedRow() > -1)
		{
			int projId = Integer.valueOf(String.valueOf(allProjTable.getValueAt(allProjTable.getSelectedRow(), 0)));

			Project proj = new Project();
			try
			{
				proj = projCtrl.findProjectByID(projId);
			}
			catch(SQLException e)
			{
				msgError(allProj, "Cannoted retrieve needed information");
				e.printStackTrace();
			}
			JTextPane reqDescrField_1 = new JTextPane();
			reqDescrField_1.setText(proj.getComments());
			JScrollPane scrollPane_1 = new JScrollPane(reqDescrField_1);
			scrollPane_1.setViewportView(reqDescrField_1);
			scrollPane_1.setPreferredSize(new Dimension(150, 150));
			scrollPane_1.setLocation(0, 0);
			JOptionPane.showConfirmDialog(allProj,scrollPane_1, "Comments", JOptionPane.DEFAULT_OPTION);

		}
		else
		{
			msgError(allProj, "You have not selected a project");
		}
	}

	public void addProductUsedItem()
	{
		String number = editProjQuantity.getText();

		if (Number.isNumber(number))
		{
			try
			{
				Item itemAdd = itemCtrl.searchItemByName(editProjItemCombobox.getSelectedItem().toString());

				int quantity = Integer.valueOf(number);

				if (itemAdd.getStock() >= quantity)
				{
					try
					{
						int result = projCtrl.addProductUsedItem(editingProject, itemAdd, quantity);

						if (result > 0)
						{
							editProjItemCombobox.setSelectedIndex(0);
							editProjQuantity.setText("");

							updateEditProject();
						}
						else
						{
							msgError(editProj, "Product is already in the sale list");
						}
					}
					catch (SQLException e)
					{
						msgError(editProj, "There was an error adding the product");
					}
				}
				else
				{
					msgError(editProj, "This amount exceeds the current available quantity\nCurrent stock of this item is " + itemAdd.getStock());
				}
			}
			catch (SQLException ex)
			{
				msgError(editProj, "There was an error searching for item quantity");
			}
		}
		else
		{
			msgError(editProj, "Quantity must be a valid number");
		}

	}

	private void updateEditProject()
	{
		try
		{
			ArrayList<ProjectUsedItem> projectItemList = projCtrl.getProjectItems(editingProject);

			updateEditProjectItems();
			updateEditProjectTable(projectItemList);
		}
		catch (SQLException e)
		{
			msgError(null, "Could not load project items");
		}
	}
	private void updateEditProjectItems()
	{
		try
		{
			editProjItemCombobox.removeAllItems();

			LinkedList<Item> itemList = itemCtrl.printAllItemsWithStock();

			for (Item item : itemList)
			{
				editProjItemCombobox.addItem(item.getName());
			}
		}
		catch (SQLException e)
		{
			msgError(null, "There was an error loading items");
		}
	}

	private void createProject()
	{
		boolean checkName = checkInfoName(projNameText);
		boolean checkDimension = checkInfoDimensions(dimensionsText);
		boolean checkQuantity = checkInfoGeneral(projQuantityText);
		boolean checkDrawing = checkInfoGeneral(projDrawNoText);
		boolean validLink = checkNull(linkText);
		boolean checkPrice = checkInfoGeneral(cusPriceText);

		if(checkName && checkDimension && checkQuantity && checkDrawing && checkPrice && validLink)
		{
			try
			{
				Customer cusObj = new Customer();
				try
				{
					cusObj = custCtrl.searchCustomerByName(newProjCustomerSelection.getSelectedItem().toString());

				} catch(SQLException e)
				{
					msgError(newProj, "Could not load customer information");
					e.printStackTrace();
				}
				getSubs(allSubsModel,chosenCreate);
				System.out.println("PRICE IS : " + priceCreate.get(0));
				int good = projCtrl.addNewProject(projNameText.getText(), Integer.valueOf(projDrawNoText.getText()), Integer.valueOf(projQuantityText.getText()), dimensionsText.getText().trim(), descr.getText(), cal.getPeriod(), cusObj, Double.parseDouble(cusPriceText.getText()), linkText.getText().trim(), comms.getText(),chosenCreate, priceCreate);

				if(good > 0)
				{
					msgSuccess(newProj, "Project has been added successfully");

					projNameText.setText(null);
					projDrawNoText.setText(null);
					dimensionsText.setText(null);
					projQuantityText.setText(null);
					linkText.setText(null);
					comms.setText(null);
					descr.setText(null);

					searchProjects();
				} // end if
				else if (good < 0)
				{
					msgError(newProj, "There was an error while trying to add the new project");

				}

			} // end of try
			catch(Exception e)
			{
				e.printStackTrace();
				msgError(newProj, "There was an error while trying to add a new project");
			}
		}
		else
		{
			msgError(newProj, "You cannot proceed de to errors in your unput. \n Please check and try again");
		}

	}

	private void searchProjects()
	{
		ArrayList<Project> projectList = new ArrayList<Project>();

		String clause = allProjSearch.getSelectedItem().toString().toLowerCase();
		String search = projSearch.getText();

		try
		{
			boolean active = allProjCheckbox.isSelected();

			switch (clause)
			{
				case "city":			projectList = projCtrl.searchProjectByCity(search, active); break;
				case "country":			projectList = projCtrl.searchProjectByCountry(search, active); break;
				case "name":			projectList = projCtrl.searchProjectByName(search, active); break;
				case "customer":		projectList = projCtrl.searchProjectByCustomer(search, active); break;
				case "everything":		projectList = projCtrl.searchProjectByEverything(search, active); break;
			}

			if (projectList.size() > 0)
				updateTableAllProjects(projectList);
			else
				tableClearList(allProjTable);
		}
		catch (Exception e)
		{
			msgError(allProj, "Could not load projects");
			e.printStackTrace();
		}

		if (!startup)
			startup = true;
	}

	private void updateTableAllProjects(ArrayList<Project> projectList)
	{
		if (projectList.size() > 0)
		{
			tableClearList(allProjTable);

			for(Project project : projectList)
			{
				allProjTableModel.addRow(
						new Object[]
								{ 
								project.getServiceID(),
								project.getDrawingNo(),
								project.getName(),
								project.getDimensions(),
								project.getPrice(),
								project.getProdQuantity(),
								project.getDeadline(),
								project.getCustomer().getCity().getName(),
								project.getCustomer().getCity().getCountry().getName(),
								project.getCustomer().getUsername()
								} 
						);
			}
		}
	}

	private void updateEditProjectTable(ArrayList<ProjectUsedItem> projectUsedItem)
	{
		tableClearList(editProjTable);

		double itemPrice = 0.0;
		double productPrice = 0.0;

		if (projectUsedItem.size() > 0)
		{
			for(ProjectUsedItem pui : projectUsedItem)
			{
				productPrice = roundToDecimals(pui.getItem().getPrice()*pui.getItemQuantity());
				itemPrice += productPrice;

				editProjTableModel.addRow(new Object[] { pui.getItem().getItemID(), pui.getItem().getName(), pui.getItem().getPrice(), pui.getItemQuantity(), productPrice } );
			}
		}

		lblItemPrice.setText(String.valueOf(roundToDecimals(itemPrice)));
	}

	private void tableClearList(JTable table)
	{
		DefaultTableModel dm = (DefaultTableModel) table.getModel();

		while(dm.getRowCount() > 0)
			dm.removeRow(0);
	}

	private boolean checkNull(JTextField textField)
	{
		if((textField.getText().trim().length() == 0 ))
			return false;

		return true;
	}
	private boolean checkInfoName(JTextField textField)
	{

		if((textField.getText().trim().length() == 0) || (textField.getText().trim().length() > 32))
			return false;

		return true;
	}
	private boolean checkInfoGeneral(JTextField textField)
	{

		if((textField.getText().trim().length() == 0) && textField.getText().matches("\\d*"))
			return false;

		return true;
	}
	private boolean checkInfoDimensions(JTextField textField)
	{

		if((textField.getText().trim().length() == 0) || (textField.getText().trim().length() > 52))
			return false;

		return true;
	}

	private void populateProjects()
	{
		editProjCombo.removeAllItems();
		editProjCombo.addItem("Select project");

		try
		{
			ArrayList<Project> projectList = projCtrl.getAllActiveProjects();

			for(Project project : projectList)
			{
				editProjCombo.addItem(project.getName());
			}
		}
		catch(SQLException e)
		{
			msgError(null, "Could not load projects");
		}
	}

	private void populateSubContractors(JComboBox<String> combobox)
	{
		try
		{
			ArrayList<SubContractor> subContractorList = subContractorCtrl.searchSubContractorAll();

			for(SubContractor sc : subContractorList)
			{
				combobox.addItem(sc.getName());
			}
		}
		catch (SQLException e)
		{
			msgError(null, "Could not load subContractors");
		}

	}

	private void populateCustomers(JComboBox<String> combobox)
	{
		combobox.removeAllItems();

		try
		{
			ArrayList<Customer> customerList = custCtrl.getAllCustomers();

			for(Customer customer : customerList)
			{
				combobox.addItem(customer.getUsername());
			}
		}
		catch (SQLException e)
		{
			msgError(null, "Could not load customers");
		}

	}

	private void getSubs(DefaultTableModel tb,ArrayList<SubContractor> sus)
	{
		for (int i = 0; i < tb.getRowCount(); i++)
		{
			SubContractor sb = new SubContractor();
			sb.setOutsiderID(Integer.parseInt(String.valueOf(tb.getValueAt(i, 0))));
			sb.setName((String) tb.getValueAt(i, 1));
			sus.add(sb);
		}

	}
	/*
	private void editProjectFields(boolean enabled)
		{
			editProjItemCombobox.setEnabled(enabled);
			editProjQuantity.setEnabled(enabled);
			btnAddItem.setEnabled(enabled);
			btnEditItem.setEnabled(enabled);
			btnDeleteItem.setEnabled(enabled);
			lblSubcontractor_1.setEnabled(enabled);

			btnSaveChanges.setEnabled(enabled);

			if (!enabled)
				tableClearList(editProjTable);
		}
	 */
	/**
	 * Shows an error message pop-up
	 * 
	 * @param	panel 		on which panel should it show the message
	 * @param	error		the error which is printed on the pop-up window
	 * 
	 * @return	void
	 */
	private void msgError(JPanel panel, String error)
	{
		JOptionPane.showConfirmDialog(panel, error, "Error", JOptionPane.PLAIN_MESSAGE, JOptionPane.ERROR_MESSAGE);
	}

	/**
	 * Shows a success message pop-up
	 * 
	 * @param	panel 		on which panel should it show the message
	 * @param	success		the success message which is printed on the pop-up window
	 * 
	 * @return	void
	 */
	private void msgSuccess(JPanel panel, String success)
	{
		JOptionPane.showMessageDialog(panel, success, "Success", 1);
	}

	private double roundToDecimals(double number) 
	{
		int temp = (int) ((number * Math.pow(10,2)));

		return (((double) temp) / Math.pow(10,2));
	}

	public static ProjectUI getInstance()
	{
		if(instance == null)
			instance = new ProjectUI();

		return instance;
	}

	public static void main(String[] args) 
	{
		try 
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 

			ProjectUI projUI = new ProjectUI();
			projUI.display();
		}
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "Project menu could not load properly", "Error", JOptionPane.ERROR_MESSAGE);
		}
	}
	public void openLink() throws IOException
	{
		if(allProjTable.getSelectedRow() > -1)
		{
			int projID = Integer.valueOf(String.valueOf(allProjTable.getValueAt(allProjTable.getSelectedRow(), 0)));

			Project proj = new Project();

			try
			{
				proj = projCtrl.findProjectByID(projID);
			}
			catch(SQLException e)
			{
				msgError(newProj, "Cannot retrieve needed information");
				e.printStackTrace();
			}
			File dir = new File(proj.getProjLink());
			String path = dir.getAbsolutePath();
			File fold = new File(path.substring(0, path.lastIndexOf(File.separator)));
			if (Desktop.isDesktopSupported()) {
				Desktop.getDesktop().open(fold);
			}
		}
	}
}